<?php

class HModules {
	function getModuleNameById($instance_id) {
		$a = HSql::fetch2Array(HSql::doQuery("SELECT id, module_id FROM portal_modules_instances WHERE id = '$instance_id'"));
		$b = HSql::fetch2Array(HSql::doQuery("SELECT id, module_name FROM portal_modules WHERE id = '".$a[0]['module_id']."'"));		
		if (count($b) == 0) return null;
		else return $b[0]['module_name'];
	}
	
	function getModuleNameByModuleId($id) {
		$a = HSql::fetch2Array(HSql::getData('portal_modules',"WHERE id = '$id'"));
		return $a[0]['module_name'];
	}
	
	function getModuleIdByName($name) {
		$a = HSql::fetch2Array(HSql::getData('portal_modules',"WHERE module_name = '$name'"));
		return $a[0]['id'];
	}

	function getPaged($page, $size) {
		$offset = ($page - 1) * $size;
		$a = HSql::fetch2Array(HSql::getData("portal_modules","WHERE is_system = '0' LIMIT ".$offset.",".$size));
		return $a;
	}
	
	function insert($module_name) {
		try {
			HSql::doQuery("
				INSERT INTO portal_modules('module_name') 
				VALUES('".$module_name."')
			");
		}
		catch (Exception $ex) {
			throw new Exception($ex->getMessage());
		}
	}
	
	function update($id, $name) {
		try {
			// validate first
			$data = HSql::fetch2Array(HSql::getData('portal_modules',"WHERE module_name = '".trim($module_name)."'"));
			$old_data = HSql::fetch2Array(HSql::getData('portal_modules',"WHERE id = '".trim($id)."'"));
			if (count($data) == 0 && $name != $old_data[0]['module_name']) {
				// change folder
				$old_path = FRONT_MODULE_PATH.SEPARATOR.$old_data[0]['module_name'];
				$new_path = FRONT_MODULE_PATH.SEPARATOR.$name;
				rename($old_path, $new_path);
				// change in database
				HSql::doQuery("UPDATE portal_modules SET module_name = '$name' WHERE id ='$id'");
				return true;
			}
			else {
				return false;
			}
		}
		catch (Exception $ex) {
			throw new Exception($ex->getMessage());
		}
	}
	
	function delete($id) {
		try {			
			// Get module info
			$a = self::getOne($id);
			// Delete in Db
			HSql::doQuery("DELETE FROM portal_modules WHERE id = '$id'");
			// Mark directory as deleted - Adding __before
			$old_path = FRONT_MODULE_PATH.SEPARATOR.$a[0]['module_name'];		
			HCommon::deleteDir($old_path);
			return true;		
		}
		catch(Exception $ex) {
			return false;
			throw new Exception($ex->getMessage());
		}
	}
	
	function getAll($condition = null) {
		return HSql::fetch2Array(HSql::getData('portal_modules', $condition));
	}
	
	function getOne($id) {
		return HSql::fetch2Array(HSql::getData('portal_modules',"WHERE id = '$id'"));
	}
}